package com.cloud.code.annotation.proxy;

import lombok.SneakyThrows;
import org.junit.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ServiceProxyFactory {

    @SneakyThrows
    public static <T> T newInstance(Class<T> tClass){
        Aspect annotation = tClass.getAnnotation(Aspect.class);
        Class type = annotation.Type();

        AspectImp aspectImp = (AspectImp) type.getConstructor().newInstance();

        return (T) Proxy.newProxyInstance(tClass.getClassLoader(), tClass.getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                aspectImp.before();
                Object invoke = method.invoke(tClass.getConstructor().newInstance(),args);
                aspectImp.after();

                return invoke;
            }
        });

    }

    @Test
    public void test(){
        IService service = ServiceProxyFactory.newInstance(Service.class);

        service.doSome();
    }
}
